package com.negative.activities;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.negative.data.EventItem;
import com.negative.logic.DialogManager;
import com.negative.logic.MenuListener;
import com.negative.logic.TicketTypeAdapter;
import com.negative.logic.TokenExtractor;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class TicketTypeActivity extends Activity{
	public static final String OUT_OF_STOCK = "out_of_stock";
	private Context context;
	private ListView types;
	private TicketTypeAdapter adapter;
	private Button continueButton;
	private EventItem event;
	private TextView title;
	private ImageView menuButton;

	private String urlAction;
	private List<NameValuePair> hiddenParams = new ArrayList<NameValuePair>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.example_purchase_layout);

		context = this;
		event = (EventItem) this.getIntent().getSerializableExtra("Event");
		types = (ListView) findViewById(R.id.ticket_type_list);
		adapter = new TicketTypeAdapter(context);
		continueButton = (Button) findViewById(R.id.ticket_type_continue);
		continueButton.setText(R.string.order_now);
		initialize();
		String eventName = event.getName();
		final long eventID = event.getId();
		title.setText(Html.fromHtml(eventName));
		String encodedEventName = "";
		try {
			encodedEventName = URLEncoder.encode(eventName,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		final String eventUrl = getResources().getString(R.string.url_event_page) + eventID + "/" + encodedEventName ; 
		TokenExtractor extractor = new TokenExtractor(eventUrl, eventID);
		extractor.start();
		while(!extractor.isFinished());
		String token = extractor.getToken();
		final String url = createUrlWithToken(token, eventID);
		new CreateTicketTypes().execute(new String[] {url});
		continueButton.setOnClickListener(new myOnClick(eventUrl));
	}
	private String createUrlWithToken(String token, long eventID) {
		String url = "https://www.tixwise.co.il/he/event/"+
				eventID+"/"+
				token+
				"?widget%5Bwidget%5D=1&widget%5Bt_theme%5D=yellow&" +
				"widget%5Bb_theme%5D=light_blue1&widget%5Breffering_url%5D=" +
				"http%3A%2F%2Fwww.bgu4u.co.il%2Fsite.aspx%3FSiteId%3D8&widget%5Btarget%5D=top\" " +
				"scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; " +
				"overflow:hidden; width:300; height:350;\"";
		return url;
	}

	private void initialize(){
		MenuListener menuListener = new MenuListener(this);
		title = (TextView) findViewById(R.id.example_purchase_event_name);
		menuButton = (ImageView) findViewById(R.id.menu_icon);

		menuButton.setOnClickListener(menuListener);
	}

	private class CreateTicketTypes extends AsyncTask<String, Void, Void>
	{

		ProgressDialog mProgressDialog;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(TicketTypeActivity.this);
			mProgressDialog.setTitle(getString(R.string.negative_plus));
			mProgressDialog.setMessage(getString(R.string.loading));
			mProgressDialog.setIcon(R.drawable.negative_plus_icon);
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.show();
		}
		@Override
		protected Void doInBackground(String... params) {	
			String url = params[0];
			Document doc;
			try {
				doc = Jsoup.connect(url).get();
				Elements tds = doc.select("#tickets_table tbody td");
				Elements selects = doc.select("#tickets_table select" );
				Elements hidden = doc.select("#hidden_and_error_container input");
				for (Element element : hidden) {
					hiddenParams.add(new BasicNameValuePair(element.attr("name"),element.attr("value")));
				}
				urlAction = doc.select("#tickets_form").attr("action");
				int j = 0;
				for (int i = 0 ; i < tds.size() ; i = i + 3) {
					String ticketType = tds.get(i).text();
					String ticketPrice = tds.get(i + 1).text();
					String[] amounts = tds.get(i + 2).text().split(" ");
					String key = OUT_OF_STOCK;
					if (j < selects.size()){
						key = selects.get(j).attr("name");
					}
					j++;
					adapter.addRecord(ticketType, ticketPrice, amounts , key);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			types.setAdapter(adapter);
			mProgressDialog.dismiss();
		}
	}

	private class SendTicketTypeToServer extends AsyncTask<HttpPost, Void, String>
	{
		@Override
		protected String doInBackground(HttpPost... params) {
			HttpResponse res = null;
			String url = null;
			try {
				HttpClient client = new DefaultHttpClient();
				res = client.execute(params[0]);
				url = EntityUtils.toString(res.getEntity());
				JSONObject json = (JSONObject) new JSONTokener(url).nextValue();
				url = (String) json.get("url");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return url;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			Intent i = new Intent(context, PaymentFormActivity.class);
			i.putExtra("response", result);
			startActivity(i);
		}
	}

	private class myOnClick implements OnClickListener{

		private String eventUrl;

		public myOnClick(String eventUrl) {
			this.eventUrl = eventUrl;
		}

		@Override
		public void onClick(View v) {
			try {
				HashMap<String, NameValuePair> typeKey = adapter.getTypeKey();
				Collection<NameValuePair> values = typeKey.values();
				NameValuePair toIgnore = null ;
				for (NameValuePair nameValuePair : values) {
					if(nameValuePair.getName().equals(OUT_OF_STOCK)){
						toIgnore = nameValuePair;
						break;
					}
				}

				boolean fail = false;
				for (NameValuePair nameValuePair2 : values) {
					if (toIgnore != null && nameValuePair2.equals(toIgnore))
						continue;
					if (nameValuePair2.getValue().equals("0") == false){
						fail  = true;
					}
				}
				if(!fail){
					Thread t = new Thread(new Runnable() {

						@Override
						public void run() {
							DialogManager.showOKDialog(TicketTypeActivity.this, true, getString(R.string.error), getString(R.string.select_tickets_error));
							TicketTypeActivity.this.continueButton.setOnClickListener(new myOnClick(eventUrl));
						}
					});
					t.start();
					return;
				}
				String url = "https://www.tixwise.co.il" + urlAction;
				HttpPost sendPurchase = new HttpPost(url);
				sendPurchase.addHeader("Referer", eventUrl);
				sendPurchase.setHeader("Content-Type", "application/x-www-form-urlencoded");
				sendPurchase.setHeader("Host", "www.tixwise.co.il");
				sendPurchase.addHeader("Pragma", "no-cache");
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.addAll(typeKey.values());
				nvps.addAll(hiddenParams);
				HttpEntity entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
				sendPurchase.setEntity(entity);
				new SendTicketTypeToServer().execute(new HttpPost[] {sendPurchase});
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
